const fs = require('fs');
const path = require('path');
const SftpClient = require('ssh2-sftp-client');
const { config: loadEnvConfig } = require('dotenv');

const ROOT_PATH = path.resolve(__dirname, '../');
const ENV_CONFIG_PATH = path.resolve(ROOT_PATH, '.env');
loadEnvConfig({ path: ENV_CONFIG_PATH });

const SSH_SERVER_HOST = process.env.SSH_SERVER_HOST;
const SSH_SERVER_PORT = process.env.SSH_SERVER_PORT;
const SSH_SERVER_USERNAME = process.env.SSH_SERVER_USERNAME;
const SSH_SERVER_PASSWORD = process.env.SSH_SERVER_PASSWORD;

const USER_NAME = process.env.USER_NAME;
const PROJ_NAME = process.env.PROJ_NAME;
const DEPLOY_PATH = process.env.DEPLOY_PATH;

async function main() {
  if (!SSH_SERVER_HOST || !SSH_SERVER_PORT || !SSH_SERVER_USERNAME || !SSH_SERVER_PASSWORD) {
    console.log(
      'SSH_SERVER_HOST, SSH_SERVER_PORT, SSH_SERVER_USERNAME or SSH_SERVER_PASSWORD is undefined，请在 .env 中进行配置！',
    );
    process.exitCode = 1;
    return;
  }

  const client = new SftpClient('upload-server');
  const srcDistDir = path.resolve(ROOT_PATH, 'dist');
  // 部署的目录，可以根据用户名和项目名称定义
  let destDir = DEPLOY_PATH;
  if (!destDir) {
    if (!USER_NAME && !PROJ_NAME) {
      console.log(
        'DEPLOY_PATH 不存在，同时 USER_NAME 与 PROJ_NAME 也不存在，请在 .env 中进行配置！',
      );
      process.exitCode = 1;
      return;
    }
    destDir = `/home/${USER_NAME}/${PROJ_NAME}`;
  }

  try {
    await client.connect({
      host: process.env.SSH_SERVER_HOST,
      port: process.env.SSH_SERVER_PORT,
      username: process.env.SSH_SERVER_USERNAME,
      password: process.env.SSH_SERVER_PASSWORD,
    });
    client.on('upload', info => {
      console.log(`Uploaded: ${info.source}`);
    });
    const uploadRes = [];
    uploadRes.push(await client.uploadDir(srcDistDir, `${destDir}/dist`));
    if (fs.existsSync(`${path.resolve(ROOT_PATH, 'nginx.conf')}`)) {
      uploadRes.push(
        await client.fastPut(`${path.resolve(ROOT_PATH, 'nginx.conf')}`, `${destDir}/nginx.conf`),
      );
    }
    if (fs.existsSync(`${path.resolve(ROOT_PATH, 'docker-compose.yaml')}`)) {
      uploadRes.push(
        await client.fastPut(
          `${path.resolve(ROOT_PATH, 'docker-compose.yaml')}`,
          `${destDir}/docker-compose.yaml`,
        ),
      );
    }
    return uploadRes.join('\n');
  } catch (err) {
    console.error(err);
  } finally {
    client.end();
  }
}

main()
  .then(msg => {
    console.log(msg);
  })
  .catch(err => {
    console.log(`main error: ${err.message}`);
  });
